import React, { useState, useEffect, useCallback, useRef } from 'react'
import { useWindowSize } from '../hooks/useWindowSize'
import MDEditor from '@uiw/react-md-editor'
import '@uiw/react-md-editor/markdown-editor.css'
import '@uiw/react-markdown-preview/markdown.css'

interface ResponsiveEditorProps {
  content: string
  filePath: string
  onSave: (content: string) => void
  onAIAction: (action: string, text: string) => void
  onShowAIMenu: (position: { x: number; y: number }, selectedText: string) => void
  sidebarWidth: number
}

const ResponsiveEditor: React.FC<ResponsiveEditorProps> = ({
  content,
  filePath,
  onSave,
  onAIAction,
  onShowAIMenu,
  sidebarWidth
}) => {
  const [value, setValue] = useState<string>(content)
  const [isSaving, setIsSaving] = useState(false)
  const [viewMode, setViewMode] = useState<'edit' | 'preview' | 'both'>('both')
  const editorRef = useRef<any>(null)
  const { width: windowWidth, height: windowHeight } = useWindowSize()

  useEffect(() => {
    setValue(content)
  }, [content])

  // Auto-save functionality
  useEffect(() => {
    const timer = setTimeout(() => {
      if (value !== content) {
        handleSave()
      }
    }, 1000) // Auto-save after 1 second of inactivity

    return () => clearTimeout(timer)
  }, [value, content])

  const handleSave = useCallback(async () => {
    if (!isSaving && value !== content) {
      setIsSaving(true)
      try {
        await onSave(value)
      } catch (error) {
        console.error('Save failed:', error)
      } finally {
        setIsSaving(false)
      }
    }
  }, [value, content, onSave, isSaving])

  const handleKeyDown = useCallback((e: KeyboardEvent) => {
    // Ctrl/Cmd + S to save
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
      e.preventDefault()
      handleSave()
    }

    // Ctrl/Cmd + B to toggle sidebar
    if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
      e.preventDefault()
      // Note: Sidebar toggle would be handled at parent level
    }

    // Ctrl/Cmd + E to toggle edit mode
    if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
      e.preventDefault()
      const modes: Array<'edit' | 'preview' | 'both'> = ['edit', 'preview', 'both']
      const currentIndex = modes.indexOf(viewMode)
      const nextIndex = (currentIndex + 1) % modes.length
      setViewMode(modes[nextIndex])
    }

    // Ctrl/Cmd + P to toggle preview
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
      e.preventDefault()
      setViewMode(viewMode === 'preview' ? 'both' : 'preview')
    }
  }, [handleSave, viewMode])

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [handleKeyDown, viewMode])

  const handleTextSelect = useCallback(() => {
    const selection = window.getSelection()

    if (selection && selection.toString().trim()) {
      // 处理在预览模式或普通DOM元素中的选中文本
      const range = selection.getRangeAt(0)
      const rect = range.getBoundingClientRect()
      onShowAIMenu(
        { x: rect.left, y: rect.bottom },
        selection.toString()
      )
    } else {
      // 处理在编辑模式（textarea）中的选中文本
      const editorElement = editorRef.current?.container?.querySelector('textarea')
      if (editorElement) {
        const textarea = editorElement as HTMLTextAreaElement
        if (textarea.selectionStart !== textarea.selectionEnd) {
          const selectedText = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)

          // 创建一个临时div来测量选中文本的位置
          const tempDiv = document.createElement('div')
          const computedStyle = window.getComputedStyle(textarea)

          // 复制textarea的样式
          tempDiv.style.position = 'absolute'
          tempDiv.style.visibility = 'hidden'
          tempDiv.style.whiteSpace = 'pre-wrap'
          tempDiv.style.wordWrap = 'break-word'
          tempDiv.style.fontSize = computedStyle.fontSize
          tempDiv.style.fontFamily = computedStyle.fontFamily
          tempDiv.style.lineHeight = computedStyle.lineHeight
          tempDiv.style.padding = computedStyle.padding
          tempDiv.style.width = textarea.offsetWidth + 'px'

          // 设置文本内容（从开始到选中结束的位置）
          const textBeforeSelection = textarea.value.substring(0, textarea.selectionEnd)
          tempDiv.textContent = textBeforeSelection

          document.body.appendChild(tempDiv)

          // 计算光标位置
          const rect = textarea.getBoundingClientRect()
          const tempRect = tempDiv.getBoundingClientRect()

          // 计算选中结束位置的坐标
          const x = rect.left + parseInt(computedStyle.paddingLeft)
          const y = rect.top + parseInt(computedStyle.paddingTop) + tempRect.height

          document.body.removeChild(tempDiv)

          onShowAIMenu(
            { x, y },
            selectedText
          )
        }
      }
    }
  }, [onShowAIMenu])

  const getSelectedText = useCallback(() => {
    const selection = window.getSelection()

    // 首先尝试获取普通DOM选中文本
    if (selection && selection.toString().trim()) {
      return selection.toString()
    }

    // 如果没有普通选中文本，尝试获取textarea中的选中文本
    const editorElement = editorRef.current?.container?.querySelector('textarea')
    if (editorElement) {
      const textarea = editorElement as HTMLTextAreaElement
      if (textarea.selectionStart !== textarea.selectionEnd) {
        return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)
      }
    }

    return ''
  }, [])

  const handleAIAction = useCallback((action: string) => {
    const selectedText = getSelectedText()
    if (selectedText.trim()) {
      onAIAction(action, selectedText)
    }
  }, [onAIAction, getSelectedText])

  // Calculate dynamic dimensions based on window size and sidebar width
  const getEditorWidth = () => {
    if (windowWidth === 0) return '100%' // Fallback for initial render
    // Handle collapsed sidebar state - if sidebarWidth is 0 or very small, assume collapsed
    const sidebarPixels = sidebarWidth && sidebarWidth > 50 ? sidebarWidth : 0
    const availableWidth = windowWidth - sidebarPixels
    return Math.max(400, availableWidth)
  }

  const getEditorHeight = () => {
    if (windowHeight === 0) return '100%' // Fallback for initial render
    // Account for header and footer space
    const availableHeight = windowHeight - 32 // Header + footer space
    return Math.max(300, availableHeight)
  }

  // Responsive view mode adjustment
  const getResponsiveViewMode = () => {
    if (windowWidth < 768) {
      // On mobile, default to edit mode
      return viewMode === 'both' ? 'edit' : viewMode
    }
    return viewMode
  }

  return (
    <div
      className="flex-1 flex flex-col h-full bg-white dark:bg-gray-900 min-w-0"
    >
      {/* Editor Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between px-4 sm:px-6 py-3 border-b border-gray-200/60 dark:border-gray-700/60 bg-white dark:bg-gray-900 gap-3">
        <div className="flex items-center gap-3 min-w-0">
          <div className="flex items-center gap-2 min-w-0">
            <div className="w-2 h-2 bg-green-500 rounded-full flex-shrink-0"></div>
            <div className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">
              {filePath.split('/').pop() || 'Untitled'}
            </div>
          </div>
          {isSaving && (
            <div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">
              <div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse"></div>
              <span className="hidden sm:inline">Saving...</span>
              <span className="sm:hidden">...</span>
            </div>
          )}
        </div>

        <div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
          {/* View Mode Toggle - Hide on small screens if needed */}
          <div className={`flex items-center bg-gray-100 dark:bg-gray-800 rounded-lg p-1 ${windowWidth < 640 ? 'scale-90' : ''}`}>
            <button
              onClick={() => setViewMode('edit')}
              className={`px-2 sm:px-3 py-1.5 rounded text-xs font-medium transition-all duration-200 ${
                getResponsiveViewMode() === 'edit'
                  ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
              }`}
            >
              <span className="hidden sm:inline">Edit</span>
              <span className="sm:hidden">✏️</span>
            </button>
            <button
              onClick={() => setViewMode('preview')}
              className={`px-2 sm:px-3 py-1.5 rounded text-xs font-medium transition-all duration-200 ${
                getResponsiveViewMode() === 'preview'
                  ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                  : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
              }`}
            >
              <span className="hidden sm:inline">Preview</span>
              <span className="sm:hidden">👁️</span>
            </button>
            {windowWidth >= 640 && (
              <button
                onClick={() => setViewMode('both')}
                className={`px-3 py-1.5 rounded text-xs font-medium transition-all duration-200 ${
                  viewMode === 'both'
                    ? 'bg-white dark:bg-gray-700 text-blue-600 dark:text-blue-400 shadow-sm'
                    : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
                }`}
              >
                Split
              </button>
            )}
          </div>

          {/* Word Count */}
          <div className="text-xs text-gray-500 dark:text-gray-400 font-medium">
            <span className="hidden sm:inline">
              {value.split(/\s+/).filter(word => word.length > 0).length} words
            </span>
            <span className="sm:hidden">
              {value.split(/\s+/).filter(word => word.length > 0).length}
            </span>
          </div>
        </div>
      </div>

      {/* Main Editor */}
      <div className="flex-1 min-h-0 overflow-hidden">
        <MDEditor
          ref={editorRef}
          value={value}
          onChange={(val) => setValue(val || '')}
          preview={getResponsiveViewMode() === 'preview' ? 'preview' : (getResponsiveViewMode() === 'edit' ? 'edit' : 'live')}
          height="100%"
          hideToolbar={false}
          textareaProps={{
            placeholder: 'Start typing your markdown here...',
            style: {
              fontSize: windowWidth < 768 ? '14px' : '15px',
              lineHeight: '1.6',
              fontFamily: '"SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas, "Courier New", monospace'
            } as React.CSSProperties,
            onMouseUp: handleTextSelect,
            onSelect: handleTextSelect
          }}
          onMouseUp={handleTextSelect}
          onBlur={handleSave}
          data-color-mode={document.documentElement.classList.contains('dark') ? "dark" : "light"}
        />
      </div>

      {/* Status Bar */}
      <div className="h-7 px-4 sm:px-6 bg-gray-50/50 dark:bg-gray-800/30 border-t border-gray-200/60 dark:border-gray-700/60 flex items-center justify-between text-xs text-gray-500 dark:text-gray-400 flex-shrink-0">
        <span className="truncate max-w-xs sm:max-w-md font-medium">
          {filePath.split('/').pop() || 'Untitled'}
        </span>
        <span className="hidden sm:inline text-gray-400 dark:text-gray-500">
          Ctrl+E 模式切换 • Ctrl+P 预览 • 选中文本呼出AI助手
        </span>
      </div>
    </div>
  )
}

export default ResponsiveEditor